package com.zlq.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zlq.reggie.common.R;
import com.zlq.reggie.dto.DishDto;
import com.zlq.reggie.entity.*;
import com.zlq.reggie.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@RestController
@RequestMapping("dish")
@Slf4j
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private CategorySercice categorySercice;

    @Autowired
    private SetmealDishService setmealDishService;

    @Autowired
    private SetmealService setmealService;

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto){
        log.info(dishDto.toString());
        dishService.saveWithFlavor(dishDto);
        String key = "dish_"+dishDto.getCategoryId()+"_1";
        redisTemplate.delete(key);
        return R.success("新增菜品成功");
    }

    @GetMapping("/page")
    public R<Page> page(int page,int pageSize,String name) {
        log.info("初始化分页.....");
        Page<Dish> objectPage = new Page<>(page, pageSize);
        Page<DishDto> pageInfo = new Page<>();
        LambdaQueryWrapper<Dish> lambdaQueryWrapper = new LambdaQueryWrapper();
        //添加过滤条件
        lambdaQueryWrapper.like(name != null,Dish::getName,name);
        //排序条件
        lambdaQueryWrapper.orderByDesc(Dish::getUpdateTime);

        dishService.page(objectPage,lambdaQueryWrapper);

        //对象拷贝
        BeanUtils.copyProperties(objectPage,pageInfo,"records");

        List<Dish> records = objectPage.getRecords();
        List<DishDto> list = records.stream().map((item) ->{
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item,dishDto);
            Long categoryId = item.getCategoryId();
            Category category = categorySercice.getById(categoryId);
            if (category != null){
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            return dishDto;
        }).collect(Collectors.toList());

        pageInfo.setRecords(list);
        return R.success(pageInfo);
    }

    /**
     * 根据id查询菜品信息和口味
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> dishShow(@PathVariable Long id){
        log.info("根据id查询菜品信息和口味....");
        DishDto byIdWithFlavor = dishService.getByIdWithFlavor(id);
        return R.success(byIdWithFlavor);
    }

    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto){
        log.info("更新菜品信息和口味信息....");
        dishService.updateWithFlavor(dishDto);
//        Set keys = redisTemplate.keys("dish_*");
//        redisTemplate.delete(keys);

        String key = "dish_"+dishDto.getCategoryId()+"_1";
        redisTemplate.delete(key);
        return R.success("新增菜品成功");
    }

    @PostMapping("/status/{status}")
    public R<String> status(@PathVariable("status") Integer status,@RequestParam List<Long> ids){
        log.info("套餐起售停售状态修改....");
        dishService.statusUpdate(status,ids);
        return R.success("起售状态修改成功");
    }

    /**
     * 判断菜品是否删除
     * @param ids
     * @return
     */
    @DeleteMapping
    public R<String> delete(@RequestParam("ids") List<Long> ids){
        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(ids != null,SetmealDish::getDishId,ids);
        //根据id查询是否包含套餐Setmeal_dish
        log.info("根据id查询是否包含套餐Setmeal_dish.....");
        List<SetmealDish> setmealDishList = setmealDishService.list(queryWrapper);
        //判断菜品是否关联
        if (setmealDishList.size() == 0){
            deleteFlavor(ids);
            return R.success("菜品删除成功");
        }
        //判断是否包含套餐
        ArrayList<Long> setmealIds = new ArrayList<>();
        for (SetmealDish setmealDish: setmealDishList) {
            //获取套餐ID
            Long setmealId = setmealDish.getSetmealId();
            setmealIds.add(setmealId);
        }
        //查询是否关联套餐
        LambdaQueryWrapper<Setmeal> setmealQueryWrapper = new LambdaQueryWrapper<>();
        setmealQueryWrapper.in(Setmeal::getId,setmealIds);
        //查询套餐
        log.info("查询套餐......");
        List<Setmeal> setmealList = setmealService.list(setmealQueryWrapper);
        for (Setmeal setmeal : setmealList){
            Integer status = setmeal.getStatus();
            if (status == 1){
                return R.success("删除的菜品中有关联在售套餐，删除失败");
            }
        }
        deleteFlavor(ids);
        return R.success("菜品删除成功");
    }

    public void deleteFlavor(List<Long> ids){
        log.info("开始删除口味数据.........");
        //这个方法有起售状态不能删除
        dishService.deleteByIds(ids);
        LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(DishFlavor::getDishId,ids);
        //删除口味
        dishFlavorService.remove(lambdaQueryWrapper);
    }

    /**
     * 根据条件查询对应的菜品数据
     * @param dish
     * @return
     */

    @GetMapping("list")
    public R<List<DishDto>> list(Dish dish){
        List<DishDto> dishDtoList = null;
        String key = "dish_"+dish.getCategoryId()+"_"+dish.getStatus();

        dishDtoList = (List<DishDto>) redisTemplate.opsForValue().get(key);
        if (dishDtoList != null){
            return R.success(dishDtoList);
        }
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(dish.getCategoryId() != null,Dish::getCategoryId,dish.getCategoryId());
        //只查询状态为再售的数据
        queryWrapper.eq(Dish::getStatus,1);
        //添加排序条件
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> list = dishService.list(queryWrapper);

        //移动端需要口味需要添加进DishDto里面
        dishDtoList = list.stream().map((item) ->{
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item,dishDto);
            Long categoryId = item.getCategoryId();
            Category category = categorySercice.getById(categoryId);
            if (category != null){
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            //菜品ID
            Long id = item.getId();
            LambdaQueryWrapper<DishFlavor> wrapper = new LambdaQueryWrapper();
            wrapper.eq(DishFlavor::getDishId,id);
            List<DishFlavor> dishFlavors = dishFlavorService.list(wrapper);
            dishDto.setFlavors(dishFlavors);
            return dishDto;
        }).collect(Collectors.toList());

        redisTemplate.opsForValue().set(key,dishDtoList,60, TimeUnit.MINUTES);
        return R.success(dishDtoList);
    }

}
